﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MySoftLab.DapFlashCore.Utils
{
    public static class CommonUtils
    {
        public static int CompareTuples((int, int, int) tuple1, (int, int, int) tuple2)
        {
            // 解构元组  
            var (a1, b1, c1) = tuple1;
            var (a2, b2, c2) = tuple2;

            // 首先比较第一个元素  
            if (a1 != a2)
            {
                return a1.CompareTo(a2);
            }

            // 如果第一个元素相等，则比较第二个元素  
            if (b1 != b2)
            {
                return b1.CompareTo(b2);
            }

            // 如果前两个元素都相等，则比较第三个元素  
            return c1.CompareTo(c2);
        }

        public static byte[] U32leListToByteList(uint[] data)
        {
            List<byte> list = new();

            foreach (var x in data)
            {
                list.Add((byte)x);
                list.Add((byte)(x >> 8));
                list.Add((byte)(x >> 16));
                list.Add((byte)(x >> 24));
            }

            return list.ToArray();
        }

        public static uint[] ByteListToU32leList(byte[] data)
        {
            List<uint> res = new List<uint>();

            for (var i = 0; i < data.Length / 4; i++)
            {
                res.Add(BitConverter.ToUInt32(data, i * 4));
            }

            return res.ToArray();
        }

        public static float U32BEToFloat32BE(uint val)
        {
            var bytes = BitConverter.GetBytes(val).Reverse().ToArray();
            return BitConverter.ToSingle(bytes, 0);
        }

        public static uint Float32beToU32be(float val)
        {
            var bytes = BitConverter.GetBytes(val).Reverse().ToArray();
            return BitConverter.ToUInt32(bytes);
        }

        public static uint AlignDown(uint value, uint multiple)
        {
            return value / multiple * multiple;
        }
    }
}
